<?php
class Api_Model_Hoadon extends Zend_Db_Table_Abstract
{
	protected $_name="hoadon";
	protected $_primary="Sophieu";

	var $Sophieu, $IdBan, $Tongtienthanhtoan, $Tienthanhtoan, $Khachdua, $Tralai, $Thoigianthanhtoan, $Ghichu, $Giamgia; 

	public function __construct() {
		$this->_name = Zend_Registry::get('tablePrefix') . $this->_name;

		parent::__construct();
	}
	
	public function Luuhoadon($lstIdLuutamDachon = '(0)')
	{
	    $data = array(
	    	'Sophieu' => $this->Sophieu,
	    	'IdBan' => $this->IdBan,
	    	'Tongtienthanhtoan' => $this->Tongtienthanhtoan,
	    	'Khachdua' => $this->Khachdua,
	    	'Tralai' => $this->Tralai,
	    	'Thoigianthanhtoan' => $this->Thoigianthanhtoan,
	    	'Ghichu' => $this->Ghichu,
	    	'Giamgia'=>$this->Giamgia,
	    	'Tienthanhtoan' => $this->Tienthanhtoan
	    );
	    $this->insert($data);
	    
	    $sohoadonhientai = $this->getAdapter()->lastInsertId();
	    
	    //Update chi tiet
	    $obLuutam = new Api_Model_Luutam();
	    $obLuutam->Sohoadon = $sohoadonhientai;
	    $obLuutam->IdBan = $this->IdBan;
	    $obLuutam->UpdateSohoadon($lstIdLuutamDachon);
	    
	    return $sohoadonhientai;
	}
	
	
	public function getdshoadontheongay($_tungay, $_denngay)
	{
	    
	    $query = $this->_db->select()
	    					->from(array('T1'=>'os_hoadon'))
	    					->joinLeft(array('T2' => 'os_dmban'), 'T1.IdBan = T2.Id', array('T2.Ten'))
	    					->where("Thoigianthanhtoan Between '$_tungay' And '$_denngay'");
	    
	    $stmt = $this->_db->query($query);
	     
	    return $result = $stmt->fetchAll();
	}
	
	public function getdshoadontheoId($id)
	{
		 
		$query = $this->_db->select()
							->from(array('T1'=>'os_hoadon'))
							->joinLeft(array('T2' => 'os_dmban'), 'T1.IdBan = T2.Id', array('T2.Ten'))
							->where("Sophieu = '$id'");
		
		$stmt = $this->_db->query($query);
		
		$obHoadon = $stmt->fetchAll();
		
		
		$query = $this->_db->select()
							->from(array('T1'=>'os_luutam'), array('Sohoadon', 'IdMon', 'Count(IdMon) as Soluong' ))
							->joinLeft(array('T2' => 'os_dmhanghoadv'), 'T1.IdMon = T2.Id', array('T2.Ten', 'T2.GiaBan') )
							->group('T1.Sohoadon')
							->where("T1.Sohoadon = '$id'")
							->group('T1.IdMon');
		
		$stmt = $this->_db->query($query);
		
		$obHoadon[0]['Chitiet'] = $stmt->fetchAll();
				
		return $obHoadon[0];
	}
	
	public function xoaHoadonById()
	{
	    
		return $this->delete("Sophieu = '$this->Sophieu'");
	}
	
}